package com.crazyhat.crazyhat.utils;

import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.PutObjectResult;


/**
 * 华为OBS服务
 */
public class ObsUtil {

    private static final String OSS_ACCESS_KEY_ID;
    private static final String OSS_ACCESS_KEY_SECRET;
    private static final String endpoint;
    private static final String bucketName;
    //private static final String region;

    private static final String urlPrefix;
    private static final String defaultUrl;

    static {

        // // //使用环境变量初始化
        // // OSS_ACCESS_KEY_ID=System.getenv("OSS_ACCESS_KEY_ID");
        // // OSS_ACCESS_KEY_SECRET=System.getenv("OSS_ACCESS_KEY_SECRET");
        // // endpoint=System.getenv("endpoint");
        // // bucketName=System.getenv("bucketName");
        // // region=System.getenv("region");

        // try{

        //     /*
        //      * 从环境变量中获取访问凭证。
        //      * 运行本代码示例之前，
        //      * 请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        //      */
        //     EnvironmentVariableCredentialsProvider credentialsProvider;
        //     credentialsProvider=CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        // } catch (ClientException e) {
        //     e.printStackTrace();
        // }

        //FIXME: 从环境变量中获取访问凭证

        //硬编码初始化
        OSS_ACCESS_KEY_ID="LTAI5tNLKg5bJqoWTfE7F8TV";
        OSS_ACCESS_KEY_SECRET="CamuvHp799UttRdombWsfsGMD3qAxx";
        endpoint="https://oss-cn-beijing.aliyuncs.com";
        bucketName="crazyhat";
        //region="cn-beijing";

        urlPrefix="https://"+bucketName+"."+endpoint.substring(endpoint.lastIndexOf("/")+1)+"/";
        defaultUrl="https://crazyhat.oss-cn-beijing.aliyuncs.com/img/52b9a020-7117-40e8-8c69-ae74c8e88785.jpg";
    }

    /**
     * 上传输入流对象到OBS,返回输入流对象的公网地址，
     * @param objectName
     * @param inputStream
     * @return
     */
    public static String uploadFile(String objectName, InputStream inputStream){

        CredentialsProvider credentialsProvider=new DefaultCredentialProvider(OSS_ACCESS_KEY_ID,OSS_ACCESS_KEY_SECRET);

        // ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        // OSS ossClient = OSSClientBuilder.create()
        //         .endpoint(endpoint)
        //         .credentialsProvider(credentialsProvider)
        //         .clientConfiguration(clientBuilderConfiguration)
        //         .region(region)
        //         .build();

        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        //公网访问地址
        String url = defaultUrl;

        try {

            PutObjectResult putObjectResult=ossClient.putObject(bucketName, objectName, inputStream);

            //System.out.println(putObjectResult.getResponse().getStatusCode());
            url = urlPrefix+objectName;

        } catch (Exception e) {

            e.printStackTrace();

            url=e.getMessage();

        } finally {

            if (ossClient!=null) {
                // 关闭OSSClient。
                ossClient.shutdown();
            }
        }

        return url;
    }

    /**
     * 删除OSS上的文件，返回删除结果
     * @param ossUrl
     * @return 成功：true，失败：false
     */
    public static boolean deleteFile(String objectUrl) {

        if (objectUrl==null) {
            return false;
        }

        CredentialsProvider credentialsProvider=new DefaultCredentialProvider(OSS_ACCESS_KEY_ID,OSS_ACCESS_KEY_SECRET);

        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        boolean isSucess=false;

        try {
            URI uri = new URI(objectUrl);

            if (bucketName.equals(uri.getHost().split("\\.")[0])) {
                String objectName = uri.getPath().substring(1); // 移除开头的'/'

                // 删除指定的Object。
                ossClient.deleteObject(bucketName, objectName);

                isSucess=true;
            }
        } catch (URISyntaxException e) {

            System.err.println("Invalid URL format.");

            e.printStackTrace();

        } finally {

            // 关闭OSSClient。
            ossClient.shutdown();
        }

        return isSucess;
    }
}
